﻿using System.Collections.Generic;
using System.Linq;

namespace System
{
    /// <summary>
    /// Extension methods for <seealso cref="System.Type"/>.
    /// </summary>
    public static class TypeExtensions
    {
        /// <summary>
        /// Gets all base types for the type this extension method is ran against. 
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The array returned contains each base type along with it's base type.</returns>
        public static Type[] GetAllBaseTypes(this Type type)
        {
            var baseTypes = new List<Type>();
            var currentBase = type.BaseType;

            while (currentBase != null)
            {
                baseTypes.Add(currentBase);
                currentBase = currentBase.BaseType;
            }

            return baseTypes.ToArray();
        }

        /// <summary>
        /// Determines whether the type is an implementation of the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="interfaceType">The interface type to check against.</param>
        /// <returns>
        /// 	<c>true</c> if [is implementation of] [the specified type]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsImplementationOf(this Type type, Type interfaceType)
        {
            return type.GetInterfaces().Any(interfaceType.Equals);
        }

        /// <summary>
        /// Determines whether the type is an implementation of the specified type.
        /// </summary>
        /// <typeparam name="T">The interface type to check against.</typeparam>
        /// <param name="type">The type.</param>
        /// <returns>
        /// 	<c>true</c> if [is implementation of] [the specified type]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsImplementationOf<T>(this Type type)
        {
            return IsImplementationOf(type, typeof (T));
        }
    }
}
